/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.im.controller;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.model.User;
import com.yami.shop.im.bean.ImRecord;
import com.yami.shop.im.bo.SysSessionInfo;
import com.yami.shop.im.bo.UserSessionInfo;
import com.yami.shop.im.param.SysUserParam;
import com.yami.shop.im.service.ImRecordService;
import com.yami.shop.im.socket.PlatformWebSocketServer;
import com.yami.shop.im.util.SecurityUtils;
import com.yami.shop.im.vo.Conversation;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/p/platform")
@Api(tags = "平台聊天接口")
@AllArgsConstructor
public class SysController {


    @Autowired
    private ImRecordService imRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShopDetailService shopDetailService;

    @GetMapping("/conversations")
    @ApiOperation(value = "最后的对话信息列表项", notes = "获取最后的对话信息列表项")
    public ResponseEntity<List<Conversation>> conversations() {
        YamiSysUser user = SecurityUtils.getSysUser();
        // 3天内的聊天记录
        List<Conversation> conversations = imRecordService.listConversationByShopId(user.getUserId(), 3,1);
        return ResponseEntity.ok(conversations);
    }
    @GetMapping("/getOnLineCustomer")
    @ApiOperation(value = "获取所有在线的客服", notes = "获取所有在线的客服")
    public ResponseEntity<List<SysUserParam>> getOnLineCustomer(SysUserParam param) {
        List<SysUserParam> infos = new ArrayList<>();
        for (Long key : PlatformWebSocketServer.SYS_MAP.keySet()) {
            SysUserParam userParam = new SysUserParam();
            SysSessionInfo sysSessionInfo = PlatformWebSocketServer.SYS_MAP.get(key);
            // 对方不在线，
            if (sysSessionInfo == null || Objects.equals(sysSessionInfo.getUserId(), SecurityUtils.getSysUser().getUserId())) {
                continue;
            }
            if(StrUtil.isNotBlank(param.getUserName()) && !sysSessionInfo.getUserName().contains(param.getUserName())){
                continue;
            }
            userParam.setUserId(sysSessionInfo.getUserId());
            userParam.setUserName(sysSessionInfo.getUserName());
            infos.add(userParam);
        }
        return ResponseEntity.ok(infos);
    }

    @PostMapping("/forwardMsg")
    @ApiOperation(value = "转发消息给目标客服", notes = "转发消息给目标客服")
    public ResponseEntity<Void> forwardMsg(@RequestBody SysUserParam param) throws IOException {
        param.setOriUserId(SecurityUtils.getSysUser().getUserId());
        imRecordService.forwardMsg(param);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/receiveMsg/{id}")
    @ApiOperation(value = "接收消息", notes = "接收用户消息")
    public ResponseEntity<Void> receiveMsg(@PathVariable("id")Long id) throws IOException{
        imRecordService.receiveMsg(id,SecurityUtils.getSysUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @GetMapping("/msgItems/{userId}")
    @ApiOperation(value = "和某人的聊天历史记录", notes = "获取和某人的聊天历史记录")
    public ResponseEntity<List<MsgItem>> msgItems(@PathVariable("userId") String userId) {
        User dbUser = userService.getUserByUserId(userId);
        YamiSysUser user = SecurityUtils.getSysUser();

        UserSessionInfo userSessionInfo = new UserSessionInfo();
        userSessionInfo.setUserId(dbUser.getUserId());
        userSessionInfo.setPic(dbUser.getPic());
        userSessionInfo.setNickName(dbUser.getNickName());

        List<ImRecord> imRecords = imRecordService.listHistory(user.getUserId(), userId, 20,1);

        List<MsgItem> msgItems = new ArrayList<>();
        for (ImRecord record : imRecords) {
            SysSessionInfo sysSessionInfo = new SysSessionInfo();
            sysSessionInfo.setUserName("系统客服");
            sysSessionInfo.setUserId(record.getBizId());
            MsgItem msgItem = imRecordService.getMsgItemByPlatform(sysSessionInfo, userSessionInfo, record);
            msgItems.add(msgItem);
        }
        // 看了和某人的聊天记录，将未读聊天记录变成已读
        imRecordService.updateToRead(userId, user.getUserId(), 0, 1);

        return ResponseEntity.ok(msgItems);
    }



}
